#include <iostream>
using std::cout;
using std::endl;

class Base {
public:
    Base(long base)
        : _base(base)
    { cout << "Base()" << endl; }

    virtual void display(){
        cout << "Base::display()" << endl;
    }

    ~Base(){ cout << "~Base()" << endl; }
private:
    long _base = 10;
};


class Derived
: public Base 
{
public:
    Derived(long base,long derived)
        : Base(base)//显式调用基类的构造函数
          , _derived(derived)
    { cout << "Derived(long)" << endl; }

    ~Derived(){ cout << "~Derived()" << endl; }

    long _derived;
};

void test0(){
    Base base(1);
    Derived d1(2,3);
    Derived d2(6,8);

    /* d1 = d2; */
    base = d1; //ok
    /* d1 = base; */ 

    //基类指针指向派生类对象
    Base * pbase = &d1; //ok
    /* Derived * pderived = &base; //error */

    Base & rbase = d1; //ok
    /* Derived & rderived = base; //error */ 
}

void test1(){
    Base base(1);
    Derived d1(2,3);
    /* Base * pbase = &d1; */
    Base * pbase = &base;

    //向下转型
    //如果是合理的转换，能够成功转换成一个Derived*
    //并使用这个指针去访问成员
    //如果是不合理的转换，会返回一个空指针
    Derived * pd = dynamic_cast<Derived*>(pbase);
    if(pd){
        cout << "转换成功" << endl;
        pd->display();
    }else{
        cout << "转换失败" << endl;
    }
}

int main(void){
    test1();
    return 0;
}
